from fastapi.responses import RedirectResponse
from tortoise.exceptions import DoesNotExist

from common.config import settings
from common.utils import request_gitee
from common.utils import create_access_token
from common.utils import get_password_hash
from schemas import Response
from dao.oauth import oauth_dao


class OauthService:

    @classmethod
    def go_gitee(cls):
        return RedirectResponse(settings.GITEE_REDIRECT)

    @classmethod
    async def get_gitee_token(cls, code):
        try:
            gitee_user_info = request_gitee(code)
        except Exception:
            return Response(code=400, errmsg='gitee请求异常')

        try:
            obj = await oauth_dao.get(openid=gitee_user_info["id"])
            user = await obj.user.values()
            return Response(data={"id": user["id"], "username": user["username"],
                                  "token": create_access_token(user["id"])
                                  }
                            )
        except DoesNotExist:
            # 注册用户 默认密码 123456
            obj = await oauth_dao.create(openid=gitee_user_info["id"],
                                         username=gitee_user_info["login"],
                                         password=get_password_hash('123456')
                                         )
            user = obj.user
            return Response(data={"id": user.id, "username": user.username,
                                  "token": create_access_token(user.id)
                                  }
                            )
